package com.kwd.news.utils;

import net.ipip.ipdb.City;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

public class IPUtil {

    public static String path = File.separator + "Users" + File.separator + "lx" + File.separator + "Downloads" + File.separator + "17monipdb" + File.separator + "ipipfree.ipdb";

    private static City db;

    private static File ipFile;

    private static long lastModified = 0l;

    private static void init() {
        String file = IPUtil.class.getClassLoader().getResource("ipipfree.ipdb").getPath();
        ipFile = new File(file);

        load();
    }

    private static void load() {
        try {
            String file = IPUtil.class.getClassLoader().getResource("/ipipfree.ipdb").getPath();
            /*db = new City(new FileInputStream(ipFile));*/
            db = new City(file);
            lastModified = ipFile.lastModified();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, String> getConfig(String ip) throws Exception {
        if (db == null || ipFile == null) {
            init();
        }

        if (lastModified != ipFile.lastModified()) {
            load();
        }

        Map<String, String> info = db.findMap(ip, "CN");
        return info;
    }

}
